
const express = require("express");
const bodyParser = require("body-parser");
const projectService = require("../../node/service/projectService.js");
const { resSuc, resErr } = require('../utils/resMsg.js');

const router = express.Router();

router.get("/", (req, res) => {
    projectService.getAll().then(rows => {
        res.json(resSuc(rows));
    }).catch(err => {
        res.json(resErr(500, err.message));
    })
})


router.post("*", bodyParser.urlencoded({ extended: false }));

// Add Project
router.post("/add", (req, res) => {
    let project = req.body;

    projectService.add(project).then((lastID) => {
        res.json(resSuc(lastID));
    }).catch(err => {
        res.json(resErr(500, err.message));
    })
})

// Delete Project
router.post("/delete", (req, res) => {
    projectService.delete(req.body.id).then(() => {
        res.json(resSuc());
    }).catch(err => {
        res.json(resErr(500, err.message));
    })
})

// Update Project
router.post("/update", (req, res) => {
    let project = req.body;

    projectService.update(project).then(() => { 
        res.json(resSuc());
    }).catch(err => {
        res.json(resErr(400, err.message));
    })
})

// 保存数据到本地js文件
router.post("/save", (req, res) => {
    projectService.saveAllProjects().then(() => {
        res.json(resSuc())
    }).catch(err => {
        res.json(resErr(400, err.message));
    })
})

module.exports = router;

